<?php

/*
 *  Generate the ListingsMap and ListingsList views with the requested location  and taxonomy values
 *  Also do url validation
 */
function listing_location_search_view() {
  global $LOC;
  if (variable_get('listing_location_countries', 0)) {
    // First we get the current arguments in the url and check that the views exist
    $args = _listing_location_analyze_url();
    if (!variable_get('listing_location_views', 0)) {
	  return t('The required views for this module are not properly installed.  Please check instructions', 'error');
    }

    //  We use either the city select search form adn view or the location search form and view depending on what is selected
    $views = array();
    if (variable_get('listing_location_include_map', 1) && variable_get('location_settings_node_activity','')!='') {
      if (variable_get('listing_location_select_search', 0)) $views[] = 'ListingsMapbyCity';
      else $views[] = 'ListingsMap';
    }
    // When we use the city select option we do not need the proximity filter but use a different filter
    if (variable_get('listing_location_select_search', 0)) $views[] = 'ListingsListbyCity';
    else $views[] = 'ListingsList';
  
    if (variable_get('listing_location_select_search', 0)) $form = drupal_get_form('listing_location_select_search_form');
    else  $form = drupal_get_form('listing_location_proximity_search_form');
  
    $list = '';
    foreach ($views as $view_name) {
      $view = views_get_view($view_name);

	  // Add a hook so that other modules can modify the view before we modify anything
	  foreach (module_implements('listing_location_search_preview') as $module) {
	    $func = $module.'_listing_location_search_preview';
	    $func($view);
	  }
	  if ($view->name=="ListingsListbyCity" || $view->name=="ListingsMapbyCity") {
	    if ($_SESSION['listings']['targeted_search'] == 'all cities') {
	      unset($view->display['default']->display_options['filters']['city']);
	    } else {
	      $parts = explode(': ', $_SESSION['listings']['targeted_search']);
	      $view->display['default']->display_options['filters']['city']['value'] = $parts[0];
	    }
	  }
	  if ($view->name=="ListingsMap" || $view->name=="ListingsMapbyCity") {
	    //  For the map we zoom on the search center of focus
	    if ($_SESSION['listings']['targeted_search'] == 'all cities') $parts = explode(":", variable_get('listing_default_location', 'Chicago: IL'));
	    else $parts = explode(":", $_SESSION['listings']['targeted_search']);
	    $result = db_query("SELECT latitude, longitude FROM {zipcodes} WHERE LOWER(city)='%s' AND LOWER(state)='%s' AND LOWER(country)='%s'", strtolower(trim($parts[0])), strtolower(trim($parts[1])), strtolower($_SESSION['listings']['country']));
	
	    $target = db_fetch_object($result);
	    if (!empty($target->latitude) && !empty($target->longitude)) {
	      $view->display['default']->display_options['style_options']['macro'] = '[gmap zoom='.variable_get('listing_location_map_zoom', 6).' |center='.$target->latitude.','.$target->longitude.' |width='.variable_get('listing_location_map_width', 300).'px |height='.variable_get('listing_location_map_height', 200).'px |control=Small |type=Map]';
	    }
	  }
	  // When using zipcodes we do this
	  if ($args['zip']=="zip" && variable_get('listing_location_include_zipcode', 0)) {
	    // Country validation
	    /*
	  if (arg(1)!='us') {
	    drupal_set_message('The database currently only supports US based listings');
	    drupal_goto(LISTING_URL.'/specialty/all');
	  }
	  */
	    if ($args['city']=="all") {
	      foreach (variable_get('listing_location_content_types', array()) as $name => $type) {
	        $view->display['default']->display_options['filters']['type']['value'][$name] = $name;
		  }
		  $type = 'all';
	    }
	    else {
	      $type = db_result(db_query("SELECT type FROM {node_type} WHERE LOWER(name)='%s'", str_replace("-"," ", $args['city'])));
	      $view->display['default']->display_options['filters']['type']['value'] = array($type => $type);
		  $type = str_replace("-"," ", $args['type']);  // use later for page title
	    }
	    if ($args['type']=="all" || $args['type']=='') {
	      if ($view_name=="ListingsMap" || $view_name=="ListingsMapbyCity") $list = listing_location_category_list();
	      unset($view->display['default']->display_options['filters']['tid']);
	    }
	    else {
	      if ($LOC->tid>0) $view->display['default']->display_options['filters']['tid']['value'][0] = $LOC->tid;
	    }
	    if (is_numeric($args['term']))  {
	      $view->display['default']->display_options['filters']['targeted_proximity']['value']['search_distance'] = $args['term'];
	    }
	    $zip = TRUE;
	    $location = $_SESSION['listings']['targeted_search'];
	    // this needs to happen after the distance has been calculated to ensure that these listings have the same distance calculation as the view
	  }
	  // when not using zipcode we do this
	  else {
	    // Do we still need this??
	    if (arg(2)=="map") return listing_location_map(arg(1));
	  
	    //if (arg(1)=="reset") return 'location has been reset';
        if (variable_get('listing_location_show_province_url', 1) && !isset($args['state'])) {
	      $countries = location_get_iso3166_list();
	      drupal_set_title(t('!states in !country', array('!states' => ucfirst(variable_get('listing_province_name', 'province')).'s', '!country' => $_SESSION['listings']['country'])));
	      return listing_location_state_list($args['country']);
	    }
	  
	    if (!isset($args['city']) || $args['city']=='') {
	      //return listing_location_cities_by_state_block(arg(2));
	    }
	  
	    if ($args['type']=="all") {
	      foreach (variable_get('listing_location_content_types', array()) as $name => $type) {
	        $view->display['default']->display_options['filters']['type']['value'][$name] = $name;
		  }
		  $type = 'all';
	    }
	    else {
	      $type = db_result(db_query("SELECT type FROM {node_type} WHERE LOWER(name)='%s'", str_replace("-"," ", $args['type'])));
	      $view->display['default']->display_options['filters']['type']['value'] = array($type => $type);
		  $type = str_replace("-"," ", $args['type']);  // use later for page title
	    }
	  
	    if ($args['term']=="all" || $args['term']=='' || !isset($args['term'])) {
	      unset($view->display['default']->display_options['filters']['tid']);
	    }
	    else {
	      if ($LOC->tid>0) $view->display['default']->display_options['filters']['tid']['value'][0] = $LOC->tid;
	    }
	    if (is_numeric(arg(6)) && !variable_get('listing_location_select_search', 0))  {
	      $view->display['default']->display_options['filters']['targeted_proximity']['value']['search_distance'] = arg(6);
	    }
	    $parts = explode(":", $_SESSION['listings']['targeted_search']);
	    $city_parts = explode(" ", $args['city']);
	    foreach ($city_parts as $key => $part) $city_parts[$key] = ucfirst($part);
	    $location['city'] = implode(" ",$city_parts);
	    if ($parts[0] == 'all cities') $location['state'] = $args['state'];
	    else $location['state'] = strtoupper($parts[1]);
	    $location['state'] = $args['state'];
	    // this needs to happen after the distance has been calculated to ensure that these listings have the same distance calculation as the view
	    if ($args['term']=="all" || $args['term']=='' || !isset($args['term'])) {
	      if ($view_name=="ListingsMap" || $view_name=="ListingsMapbyCity") $list = listing_location_category_list();
	    }
	  }
	  // Add a hook so that other modules can modify the view after we have applied the programmatic filters
	  foreach (module_implements('listing_location_search_view') as $module) {
	    //drupal_set_message('mod '.$module);
	    $func = $module.'_listing_location_search_view';
	    $func($view);
	  }
	  $output = $view->preview();
      $view->execute();
	  if ($view_name=="ListingsMap" || $view_name=="ListingsMapbyCity") $result = $form.$list.$output;
	  else $result .= $form.$output;		
    }
 	$args = _listing_location_analyze_url();
	$args = listing_location_strings_from_args($args);
	$title = theme('listing_location_page_title', $args);
	drupal_set_title($title);
    return $result;
  }
  else return t('The listing location module only works when data is present in the location module zipcodes table and <a href="/admin/listing/location_search/general">listing location settings</a> have been applied.  Please read instructions.');
}

function listing_location_autocomplete($string = '') {
  $matches = array();
  if (is_numeric($string)) {
    print drupal_to_js('');
    exit();
  }
  else {
	$string = check_plain(str_replace("'", "", $string));
    $result = db_query("SELECT zip, city, state, country FROM {zipcodes} WHERE LOWER(city) LIKE LOWER('%".$string."%') OR LOWER(city) LIKE LOWER('".$string."%')");
     while ($loc = db_fetch_object($result)) {
        $matches[$loc->city.': '.$loc->state] = check_plain($loc->city).', '.check_plain($loc->state).', '.check_plain($loc->country);
    }
  }
  print drupal_to_js($matches);
  exit();
}
function listing_location_get_select_terms($type, $selected_tid) {
  $terms = listing_get_listing_term_names();
  $output = '';
  if (is_array($terms[$type])) {
    $output .= '<option value="all">All</option>';
    foreach ($terms[$type] as $tid => $term) {
	  if ($tid == $selected_tid)  $output .= '<option selected="selected" value="'.$tid.'">'.$term.'</option>';
      else $output .= '<option value="'.$tid.'">'.$term.'</option>';
    }
  }
  print $output;
  exit();
}

// This is a general error capture menu callback that returns the user to their saved session variables
function listing_location_listing_location_default() {
  drupal_set_message('Sorry the url you supplied appears to be invalid, please try again.');
  drupal_goto(listing_location_search_url('all', '_save'));
}

/*
 *  Targeted listings
 */
// called from javascript to execute targeted listings
// First view:
// Filter: location <= 10 miles, therapist = tag, listing.type > 0
// Sort: random

// Second view:
// Filter: location >10 miles and <= 50 miles, therapist = tag, listing.type > 0
// Sort: random
// Third view:
// Filter: location <= 50 miles
// Sort: therapist = tag, listing.type > 0, location

// Fourth view:  location <= 50 miles, therapist = tag, free listing
// Sort: location

// Fifth view: location <=50 miles, therapist <> tag, enhanced listing
// Sort: location

// Sixth view: location <=50 miles, therapist <> tag, free listing
// Sort: listing, location


// Seventh view:
// Filter: location > 50 miles, therapist = tag
// Sort: location, listing.type 

// Eighth view:
// Filter: location > 50 miles, therapist <> tag
// Sort: location, listing.type 

// Default
// First backup view:
// Filter: therapist = tag, listing.type > 0
// Sort: random

// Second backup view:
// Filter: therapist = tag
// Sort: random

// Third backup view:
// Sort: listing.type > 0, random
function listing_location_get_listings() {
  include(drupal_get_path('module', 'ad_geoip').'/ad_geoip.inc');
  $delta = arg(3);
  
  if ($delta==3) $start = 1;
  else $start = 5;
  //  Loop through views
  $location = listing_location_get_targeted_search_location_text();
  // we have a problem with new visitors who have no session cookie
  if (!isset($_SESSION['listings']['targeted_search'])) {
    $location = listing_location_get_geoip();
	$output = '<h2>'.l(t('Autism Service Providers near !city, !state', array('!city' => $location['city'], '!state' => strtoupper($location['code']))), listing_location_search_url()).'</h2>';
  }
  elseif (is_numeric($_SESSION['listings']['targeted_search'])) $output = '<h2>'.l(t('Autism Service Providers near zip code !zip', array('!zip' => $_SESSION['listings']['targeted_search'])), LISTING_URL.'/specialty/all').'</h2>';
  else $output = '<h2>'.l(t('Autism Service Providers near !city, !state', array('!city' => $location['city'], '!state' => strtoupper($location['code']))), listing_location_search_url()).'</h2>';
  for ($i=$start; $i<8; $i++) {
    if ($count < variable_get('listing_location_target_list_limit', 3)) {
	  if ($i!=3) $output .= listing_location_listing_location_view($view, $i, $count);
    }
  }
  print $output;
  exit();

}
function listing_location_listing_location_view($view, $view_ind, &$count) {
    $view = views_get_view('TargetedListings'.$view_ind);

    $diff = variable_get('listing_location_target_list_limit', 3) - $count;
    $view->display['default']->display_options['items_per_page'] = $diff;
	$output = $view->preview('block');
    $view->execute('block');
    $count = $count + count($view->result);
	if (variable_get('listing_location_debug', 0)) return '<b>Result from View'.$view_ind.'</b><br />'.count($view->result) .' results<br />'.$output;		
	elseif (count($view->result)>0 ) return $output;		 
	else return;
}
